package com.jee.support.memcached;

/**
 * http://code.google.com/p/xmemcached/wiki/User_Guide_zh
 */
import java.io.IOException;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.CASOperation;
import net.rubyeye.xmemcached.KeyIterator;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.transcoders.StringTranscoder;
import net.rubyeye.xmemcached.utils.AddrUtil;

public class XMemcachedTest {

	public static void main(String[] args) throws Exception {
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(
				AddrUtil.getAddresses("localhost:11211"));
		MemcachedClient memcachedClient = builder.build();
		try {
			memcachedClient.set("hello", 0, "Hello,xmemcached");
			String value = memcachedClient.get("hello");
			System.out.println("hello=" + value);
			memcachedClient.delete("hello");
			value = memcachedClient.get("hello");
			System.out.println("hello=" + value);
		} catch (MemcachedException e) {
			System.err.println("MemcachedClient operation fail");
			e.printStackTrace();
		} catch (TimeoutException e) {
			System.err.println("MemcachedClient operation timeout");
			e.printStackTrace();
		} catch (InterruptedException e) {
			// ignore
		}
		try {
			// close memcached client
			memcachedClient.shutdown();
		} catch (IOException e) {
			System.err.println("Shutdown MemcachedClient fail");
			e.printStackTrace();
		}
		/**
		 * 首先通过gets方法获取一个GetsResponse，此对象包装了存储的数据和cas值，
		 * 然后通过cas方法尝试原子更新，如果失败打印”cas error”。显然，这样的方式很繁琐，
		 * 并且如果你想尝试多少次原子更新就需要一个循环来包装这一段代码，
		 * 因此XMemcached提供了一个*CASOperation*接口包装了这部分操作，
		 * 允许你尝试N次去原子更新某个key存储的数据，无需显式地调用gets获取cas值,上面的代码简化为:
		 * 
		 */
		memcachedClient.cas("a", 0, new CASOperation<Integer>() {
			public int getMaxTries() {
				return 1;
			}

			public Integer getNewValue(long currentCAS, Integer currentValue) {
				return 2;
			}
		});

		/**
		 * 一些更全面的例子，展现了MemcachedClient接口的主要方法：
		 */
		memcachedClient.flushAll();
		if (!memcachedClient.set("hello", 0, "world")) {
			System.err.println("set error");
		}
		if (memcachedClient.add("hello", 0, "dennis")) {
			System.err.println("Add error,key is existed");
		}
		if (!memcachedClient.replace("hello", 0, "dennis")) {
			System.err.println("replace error");
		}
		memcachedClient.append("hello", " good");
		memcachedClient.prepend("hello", "hello ");
		String name = memcachedClient.get("hello", new StringTranscoder());
		System.out.println(name);

		/**
		 * 想迭代所有的key，你只需要获取一个KeyIterator即可：
		 */
		KeyIterator it=memcachedClient.getKeyIterator(AddrUtil.getOneAddress("localhost:11211"));
		while(it.hasNext())
		{
		   String key=it.next();
		}
	}
}
